package subsystems

import (
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"strconv"
)

type CpuSetSubSystem struct {
}

func MakeCpuSetSubSystem() *CpuSetSubSystem {
	return &CpuSetSubSystem{}
}

func (this *CpuSetSubSystem) Name() string {
	return "cpuset"
}
func (this *CpuSetSubSystem) Set(cGroupPath string, resConfigPtr *ResourceConfig) error {
	if subSysCGroupPath, err := GetCGroupPath(this.Name(), cGroupPath, true); err == nil {
		if resConfigPtr.CpuSet != "" {
			if err := ioutil.WriteFile(path.Join(subSysCGroupPath, "cpuset.cpus"), []byte(resConfigPtr.CpuSet), 0644); err != nil {
				return fmt.Errorf("set cgroup cpuset fail %v", err)
			}
			return nil
		}
		return err
	} else {
		return err
	}
}
func (this *CpuSetSubSystem) Apply(cGroupPath string, pid int) error {
	if subSysCGroupPath, err := GetCGroupPath(this.Name(), cGroupPath, true); err == nil {
		if err := ioutil.WriteFile(path.Join(subSysCGroupPath, "tasks"), []byte(strconv.Itoa(pid)), 0644); err != nil {
			return fmt.Errorf("set cpu set cgroup proc fail %v", err)
		}
		return nil
	} else {
		return fmt.Errorf("get cpu set cgroup %s error: %v", cGroupPath, err)
	}
}
func (this *CpuSetSubSystem) Remove(cGroupPath string) error {
	if subSysCGroupPath, err := GetCGroupPath(this.Name(), cGroupPath, true); err == nil {
		return os.RemoveAll(subSysCGroupPath)
	} else {
		return err
	}
}
